/*    file: ScaleContext.cpp
 *    desc:
 * 
 * created: 2014-01-21 16:59:44
 *  author: zhengchuanjiang
 * company: 
 */

#include "ScaleContext.h"


ScaleContext::ScaleContext(AVPixelFormat destFmt):
    m_pContext(),
    m_fmt(AV_PIX_FMT_NONE),
    m_srcWidth(),
    m_srcHeight(),
    m_outWidth(),
    m_outHeight(),
    m_destFormat(destFmt)
{

}

ScaleContext::~ScaleContext()
{
    reset(AV_PIX_FMT_NONE);
}

void ScaleContext::reset(AVPixelFormat destFmt)
{
    if (m_pContext)
    {
        sws_freeContext(m_pContext);
        m_pContext = NULL;
    }

    m_fmt = AV_PIX_FMT_NONE;
    m_srcWidth = 0;
    m_srcHeight = 0;

    m_outWidth = 0;
    m_outHeight = 0;

    m_destFormat = destFmt;
}
 
bool ScaleContext::update(AVFrame* pFrame, int width, int height)
{
    if (width <= 0 || height <= 0)
    {
        return false;
    }

    if ((width != m_outWidth) ||
        (height != m_outHeight) || 
        (m_srcWidth != pFrame->width) ||
        (m_srcHeight != pFrame->height) ||
        (m_fmt != pFrame->format))
    {
        if (m_pContext)
        {
            sws_freeContext(m_pContext);
            m_pContext = NULL;
        }
    }

    bool changed = false;
    if (!m_pContext)
    {
        m_pContext = sws_getContext(pFrame->width,
            pFrame->height, (AVPixelFormat)pFrame->format,
            width, height,
            m_destFormat, SWS_BILINEAR, 0, 0, 0);
        if (m_pContext)
        {
            m_srcWidth = pFrame->width;
            m_srcHeight = pFrame->height;
            m_fmt = (AVPixelFormat)pFrame->format;
            m_outWidth = width;
            m_outHeight = height;

            changed = true;
        }
    }

    return changed;
}

bool ScaleContext::update(AVFrame* pFrame, int width, int height, AVPixelFormat destFmt)
{
	if (width <= 0 || height <= 0)
	{
		return false;
	}

	if ((width != m_outWidth) ||
		(height != m_outHeight) ||
		(m_srcWidth != pFrame->width) ||
		(m_srcHeight != pFrame->height) ||
		(m_fmt != pFrame->format) ||
		(m_destFormat != destFmt))
	{
		if (m_pContext)
		{
			sws_freeContext(m_pContext);
			m_pContext = NULL;
		}
	}

	m_destFormat = destFmt;

	bool changed = false;
	if (!m_pContext)
	{
		m_pContext = sws_getContext(pFrame->width,
			pFrame->height, (AVPixelFormat)pFrame->format,
			width, height,
			m_destFormat, SWS_BILINEAR, 0, 0, 0);
		if (m_pContext)
		{
			m_srcWidth = pFrame->width;
			m_srcHeight = pFrame->height;
			m_fmt = (AVPixelFormat)pFrame->format;
			m_outWidth = width;
			m_outHeight = height;

			changed = true;
		}
	}

	return changed;
}
